<?php

namespace App\Models\Order;

use App\Models\Custom\Custom;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Saleorder extends Model
{
    protected $table = 'sale_order';
    public $timestamps = false;
    protected $primaryKey = 'id';
    protected $guarded = ['_token'];

    /**
     * 判断数据是否存在
     */
    public static function isexist($id)
    {
        $isexist = self::where('id', $id)->first();
        if (!$isexist) {
            return false;
        }
        return true;
    }

    /**
     * 列表
     *
     * 销售订单审核列表/删除销售订单列表，直接使用 销售订单列表接口
     * 导致查询销售和查询销售审核，数据可能互相影响。
     * 最好接口拆开。
     *
     * 为了兼容 已删除销售订单数据，
     * if(!in_array('3',$del_status)){
     *      $query->where('is_del', config('constants.is_del.no'));
     * }
     *
     */
    public static function getList($request, $memberinfo, $isgetall)
    {
        $manger_id = $memberinfo['id'] ?? 0;
        $cpid = $memberinfo['cpid'] ?? 0;
        $utype = $memberinfo['utype'] ?? 0;

        // $sys_dpm_id = $memberinfo['sys_dpm_id'] ?? 0;
//        $suborderConditions = function ($query){
//            $query->where('is_del', config('constants.is_del.no'));
//        };

        //品名
        $archive_name = $request->archive_name;
        //规格
        $archive_spec = $request->archive_spec;
        //钢材编码
        $archive_no = $request->archive_no;
        //删除状态
        $del_status = $request->del_status ?? '';
        if (!empty($del_status)) {
            if (!is_array($del_status)) {
                $del_status = explode(',', $del_status);
            }
        }else{
            $del_status = [];
        }

        $suborderConditions = function ($query) use ($archive_name,$archive_spec,$archive_no,$del_status) {
            if(!in_array('3',$del_status)){
                $query->where('is_del', config('constants.is_del.no'));
            }
            if($archive_name !=''){
                $query->where('archive_name', 'like', '%' . $archive_name . '%');
            }
            if($archive_spec !=''){
                $query->where('archive_spec', 'like', '%' . $archive_spec . '%');
            }
            if($archive_no !=''){
                $query->where('archive_no', 'like', '%' . $archive_no . '%');
            }
        };
        $query = self::whereHas('suborder', $suborderConditions)
            ->with(['suborder' => $suborderConditions])
            ->orderBy('create_at', 'desc');

        if (!empty($del_status)) {
            $query->whereIn('del_status', $del_status);
        } else {
            $query->where('is_del', config('constants.is_del.no'));
        }

        //单据日期
        $start_time = $request->start_time;
        if ($start_time != '') {
            $query->where('document_date', '>=', $start_time);
        }

        $end_time = $request->end_time;
        if ($end_time != '') {
            $query->where('document_date', '<=', $end_time + 86341);
        }

        //客户名称
        $custom_name = $request->custom_name;
        if ($custom_name != '') {
            $query->where('custom_name', 'like', '%' . $custom_name . '%');
        }

        //单据编号
        $document_number = $request->document_number;
        if ($document_number != '') {
            $query->where('document_number', 'like', '%' . $document_number . '%');
        }

        $order_number = $request->order_number;
        if ($order_number != '') {
            $query->where('order_number', 'like', '%' . $order_number . '%');
        }

        //manger 1自己添加的数据，2所有数据  销售订单账号隔离
        $manger = $request->manger;
        if ($manger == 1 || $utype == '7') {
            $query->where('manger_id', '=', $manger_id);
        }

        //操盘，显示 需要审核或审核过的订单
        $is_audit_list = $request->is_audit_list;//默认值 传入1
        if($utype == '2'){
            if(empty($del_status)){
                if(isset($is_audit_list) && $is_audit_list == '1'){
                    $query->whereIn('order_status',['2','3','4']);
                }
            }
        }

        $order_status = $request->order_status;
        if ($order_status != '') {
            $query->where('order_status', '=', $order_status);
        }

        if ($cpid > 0) {
            $query->where('cpid', $cpid);
        }

        $order_type = $request->order_type ?? 0;
        if ($order_type > 0) {
            $query->where('order_type', '=', $order_type);
        }

        // if ($sys_dpm_id > 0) {
        //     $query->where('sys_dpm_id', $sys_dpm_id);
        // }

//        if ($utype == 2) {
//            $query->where('order_type', '<>', 1);
//        }

        if ($isgetall == 0) {
            $limit = $request->limit ?? 10;
            $list = $query->paginate($limit)->toArray();
            return paginateDataToArray($list);
        } else {
            $list = $query->get()->toArray();
            return ['list' => $list];
        }
    }

    /**
     * 低于指导价列表
     * sale_order列表字段 examine_status 状态[2 3 4] 视为低于指导价列表
     *
     */
    public static function getLowPriceList($request, $memberinfo, $isgetall)
    {
        $cpid = $memberinfo['cpid'] ?? 0;


        $query = self::with(['suborder' => function ($query) {
            $query->where('is_del', config('constants.is_del.no'));

        }])
            //->where('examine_status', config('constants.examine_status.in_review'))
            ->where('is_del', config('constants.is_del.no'))
            ->whereIn('examine_status', ['2', '3', '4'])
            ->orderBy('create_at', 'desc');

        //单据日期
        $start_time = $request->start_time;
        if ($start_time != '') {
            $query->where('document_date', '>=', $start_time);
        }

        $end_time = $request->end_time;
        if ($end_time != '') {
            $query->where('document_date', '<=', $end_time);
        }

        //客户名称
        $custom_name = $request->custom_name;
        if ($custom_name != '') {
            $query->where('custom_name', 'like', '%' . $custom_name . '%');
        }

        //销售订单号
        $order_number = $request->order_number ?? '';
        if ($order_number != '') {
            $query->where('order_number', 'like', '%' . $order_number . '%');
        }
        //单据编号
        $document_number = $request->document_number ?? '';
        if ($document_number != '') {
            $query->where('document_number', 'like', '%' . $document_number . '%');
        }

        if ($cpid > 0) {
            $query->where('cpid', $cpid);
        }


        if ($isgetall == 0) {
            $limit = $request->limit ?? 10;
            $list = $query->paginate($limit)->toArray();
            $list = paginateDataToArray($list);
        } else {
            $list['list'] = $query->get()->toArray();

        }

        if (!empty($list['list'])) {
            foreach ($list['list'] as &$item) {
                if (!empty($item['suborder'])) {
                    foreach ($item['suborder'] as &$v) {
                        $v['weight'] = mathfuncweight('div', $v['weight'], 10000, 4);
                        $v['total_weight'] = mathfuncweight('div', $v['total_weight'], 10000, 4);
                        $v['unit_price'] = mathfuncmoney('div', $v['unit_price'], 100, 2);
                        $v['total'] = mathfuncmoney('div', $v['total'], 100, 2);
                        $v['accrual'] = mathfuncmoney('div', $v['accrual'], 100, 2);
                        $v['performance'] = mathfuncmoney('div', $v['performance'], 100, 2);
                    }
                }

            }
        }

        return $list;
    }

    /**
     * 详情
     */
    public static function getone($id)
    {
        return self::with(['suborder' => function ($query) {
            $query->where('is_del', config('constants.is_del.no'));
        }])->where('id', $id)
            ->where('is_del', config('constants.is_del.no'))
            ->first();
    }

    /**
     * 获取子订单
     * 查询删除订单列表时，子订单is_del=2 为了兼容列表查询 suborder方法没有使用 is_del=1 条件
     * 记录修改销售订单日志，只记录有效子订单
     *
     */
    public function suborder()
    {
        return $this->hasMany(Saleordersub::class, 'p_id', 'id');
    }
    /**
     * 统计
     */
    public static function count($request,$cpid=0)
    {
        $page = !empty($request->page) ? $request->page - 1 : 0;
        $limit = !empty($request->limit) ? $request->limit : 10;
        $offset = $limit * $page;


        if($request->type && count($request->type)==2){
            $start_time =$request->type[0];
            $end_time =$request->type[1];

        }else{
            $now = strtotime('Y-m-d');
            $start_time = strtotime($now . ' 00:00:00');
            $end_time = strtotime($now . ' 23:59:59');
        }

        $query = DB::table('sale_order')
            ->join('sale_order_sub', 'sale_order.id', '=', 'sale_order_sub.p_id')
            ->selectRaw("from_unixtime(`huakun_sale_order`.document_date, GET_FORMAT(DATE,'ISO')) as date")
            ->selectRaw("sum(`huakun_sale_order_sub`.total_weight) as total")
            ->where([
                'sale_order.is_del' => config('constants.is_del.no'),
                'sale_order_sub.is_del' => config('constants.is_del.no'),
                'sale_order.cpid'=>$cpid
            ])
            ->where('sale_order.create_at', '>=', $start_time)
            ->where('sale_order.create_at', '<=', $end_time)
            ->groupBy('date')->orderBy('date', 'desc');

        $totalCount = count($query->get());
        $res['list'] = $query->offset($offset)->limit($limit)->get()->toarray();

        $res['page']['totalCount'] = $totalCount;
        $res['page']['currentPage'] = $page;
        $res['page']['totalPage'] = ceil($totalCount / $limit);

        return $res;
    }

    public function custom()
    {
        return $this->hasOne(Custom::class, 'id', 'custom_id');
    }
}
